const History = require("../models/historyModel.js")
const { getStockByCode } = require('./cachedController');

class HistoryController {
    async find(ctx) {
        ctx.body = await History.find();
    }
    async findById(ctx) {
        const history = await History.findById(ctx.params.id);
        if (!history) {
            ctx.throw(404, "数据不存在");
        }
        ctx.body = history;
    }
    async findByDate(date) {
        const targetDate = new Date(date);
        const startOfDay = new Date(targetDate.setHours(0, 0, 0, 0));
        const endOfDay = new Date(targetDate.setHours(23, 59, 59, 999));
        const history = await History.find({
            date: {
                $gte: startOfDay,
                $lte: endOfDay
            }
        });
        if (!history || history.length === 0) {
            return [];
        }

        return history.map(item => {
            let existStock = getStockByCode(item.code)
            return {
                '_id': item._id,
                "date": item.date,
                "code": item.code,
                "name": item.name,
                "sector": item.sector,
                "region": item.region,
                "concept": item.concept,
                "price": existStock && existStock.price || item.price,
                "changePercent": item.changePercent,
                "threeDayChange": item.threeDayChange,
                "fiveDayChange": item.fiveDayChange,
                "turnoverRate": item.turnoverRate,
                "volumeRatio": item.volumeRatio,
                "pe": item.pe,
                "pb": item.pb,
                "limitUpDays": item.limitUpDays,
                "predictionScore": item.predictionScore,
                "predictionTime": item.predictionTime,
                "predictedPrice": item.predictedPrice,
                "mainMoneyNet": item.mainMoneyNet,
            }
        });
    }
    create(data) {
        new History(data, false).save();
    }
    update(id, data) {
        History.findByIdAndUpdate(id, data);
    }
    async delete(id) {
        await History.findByIdAndRemove(id);
    }
}

module.exports = new HistoryController();